﻿using Infrastructure.Model;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Infrastructure.Extensions
{
    // 应用服务扩展类，用于注册程序集中带有 AppServiceAttribute 标记的服务类
    public static class AppServiceExtensions
    {
        // 扩展方法，用于向服务集合中注册程序集中的服务
        public static void AddAppService(this IServiceCollection services, string[] AssemblyName)
        {
            foreach (string assemblyString in AssemblyName)
            {
                Assembly assembly = Assembly.Load(assemblyString);
                Register(services, assembly); // 调用注册方法
            }
        }
        // 注册方法，根据程序集中的特性注册服务
        private static void Register(IServiceCollection services, Assembly assembly)
        {
            Type[] types = assembly.GetTypes(); // 获取程序集中所有类型
            foreach (Type type in types)
            {
                // 获取类上的 AppServiceAttribute 特性
                AppServiceAttribute customAttribute = type.GetCustomAttribute<AppServiceAttribute>();
                if (customAttribute != null)
                {
                    Type serviceType = customAttribute.ServiceType; // 特性中指定的服务类型
                    if (serviceType == null && customAttribute.InterfaceServiceType)
                    {
                        // 如果未指定具体服务类型但标记了接口服务类型，则使用第一个实现的接口作为服务类型
                        serviceType = type.GetInterfaces().FirstOrDefault();
                    }
                    if (serviceType == null)
                    {
                        serviceType = type; // 默认情况下，服务类型为类本身
                    }

                    // 根据特性中指定的生命周期注册服务
                    switch (customAttribute.ServiceLifetime)
                    {
                        case LifeTime.Singleton:
                            services.AddSingleton(serviceType, type);
                            break;
                        case LifeTime.Scoped:
                            services.AddScoped(serviceType, type);
                            break;
                        case LifeTime.Transient:
                            services.AddTransient(serviceType, type);
                            break;
                        default:
                            services.AddTransient(serviceType, type); // 默认为瞬态生命周期
                            break;
                    }
                }
            }
        }
    }
}
